<template>
  <div>
    <a-card>
      <div :class="advanced ? 'search' : null">
        <a-form layout="horizontal">
          <div :class="advanced ? null : 'fold'">
            <a-row>
              <a-col :md="8" :sm="24">
                <a-form-item label="名称" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
                  <a-input placeholder="请输入商品名称" v-model="inputForm.nickname" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="创建日期" :labelCol="{ span: 5 }" :wrapperCol="{ span: 18, offset: 1 }">
                  <a-date-picker style="width: 100%" placeholder="请输入创建日期" v-model="inputForm.createAt" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
          <span style="float: right; margin-top: 3px;">
            <a-button type="primary" @click="getData">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetInputForm">重置</a-button>
            <a @click="toggleAdvanced" style="margin-left: 8px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'" />
            </a>
          </span>
        </a-form>
      </div>
      <div>
        <a-space class="operator">
          <a-button @click="addNew" type="primary">新建</a-button>
        </a-space>
        <standard-table :columns="columns" :dataSource="dataSource" :selectedRows.sync="selectedRows" @clear="onClear"
          @change="onChange" :pagination="{ ...pagination, onChange: onPageChange }"
          @selectedRowChange="onSelectChange">
          <div slot="description" slot-scope="{text}">
            {{ text }}
          </div>
          <div slot="action" slot-scope="{text, record}">
            <a @click="deleteRecord(record)">
              <a-icon type="edit" />上下架
            </a>
            <a style="margin-right: 8px" @click="editUser(record)">
              <a-icon type="delete" />删除
            </a>
          </div>

          <template v-slot:img="{ text }">
            <a-popover>
              <template slot="content">
                <img :src="text" style="max-width: 200px; max-height: 200px;" />
              </template>
              <img :src="text" style="width: 50px; height: 50px; cursor: pointer;" />
            </a-popover>
          </template>
          <template slot="statusTitle">
            <a-icon @click.native="onStatusTitleClick" type="info-circle" />
          </template>
        </standard-table>
      </div>

    </a-card>
    <a-drawer :visible="visible" title="用户详情" placement="right" :width="736" @close="closeDrawer">

    </a-drawer>
    <a-drawer :visible="productVisible" title="新建商品" placement="left" :width="736" @close="closeProductDrawer">
      <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
        <a-form>
          <a-form-item label="商品名称" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-input placeholder="请输入商品名称" v-model="addForm.name" />
          </a-form-item>
          <a-form-item label="商品详情" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-input placeholder="请输入商品标题" v-model="addForm.title" />
          </a-form-item>
          <a-form-item label="商品大图" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-upload v-model="fileList" name="file" action="http://localhost:3002/api/v1/upload" :headers="headers"
              @change="handleChange">
              <a-button>
                请选择图片
              </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item label="商品价格" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-input placeholder="请输入商品价格" v-model="addForm.price" />
          </a-form-item>
          <a-form-item label="商品销售价格" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-input placeholder="请输入商品销售价格" v-model="addForm.discount_price" />
          </a-form-item>
          <a-form-item label="商品数量" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-input-number placeholder="请输入商品数量" v-model="addForm.num" :min="1" :max="1000" />
          </a-form-item>
          <a-form-item label="商品分类" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-cascader v-model="flistValue" :options="flist" placeholder="Please select" />
          </a-form-item>
          <a-form-item label="是否在售" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-switch v-model="addForm.on_sale" />
          </a-form-item>
          <a-form-item style="margin-top: 24px" :wrapperCol="{ span: 10, offset: 7 }">
            <a-button type="primary" @click="addProduct()">提交</a-button>
          </a-form-item>
        </a-form>
      </a-card>
    </a-drawer>
  </div>
</template>

<script>
import StandardTable from '@/components/table/StandardTable'
import { request } from '@/utils/request'
import { categorys } from '@/services/category'
import moment from 'moment';
const columns = [
  {
    title: '编号',
    dataIndex: 'key'
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '图片',
    dataIndex: 'img_path',
    key: 'img',
    scopedSlots: { customRender: 'img' },
  },
  {
    title: '是否在售',
    dataIndex: 'onsale',
    key: 'onsale',
    customRender: (text) => (text == 1 ? '是' : '否'),
  },
  {
    title: '数量',
    dataIndex: 'total_num'
  },
  {
    title: '剩余数量',
    dataIndex: 'num'
  },
  {
    title: '定价',
    dataIndex: 'price'
  },
  {
    title: '销售价格',
    dataIndex: 'discount_price'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    sorter: true,
    customRender: (text) => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss')
    },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'QueryList',
  components: { StandardTable },
  data() {
    return {
      advanced: true,
      columns: columns,
      dataSource: [],
      selectedRows: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      inputForm: {
        username: "",
        nickname: "",
        status: "",
        mobile: "",
        createAt: ""
      },
      addForm: {
        name: '',
        title: '',
        info: '',
        img_path: '',
        price: 100,
        discount_price: 99,
        on_sale: true,
        num: 1,
      },
      visible: false,
      productVisible: false,
      fileList: [],
      headers: {
        Authorization: sessionStorage.getItem('token')
      },
      categoryList: [],
      flist: [],
      flistValue: [],
      checked: false,
      imgList: []
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    addProduct() {
      let category_id = this.flistValue.join(',')
      let onsale = 0

      if (this.addForm.on_sale) {
        onsale = 1
      }

      request(process.env.VUE_APP_API_BASE_URL1 + '/products', 'post', {
        name: this.addForm.name,
        category_id: category_id,
        title: this.addForm.title,
        info: this.addForm.info,
        img_path: this.imgList,
        price: this.addForm.price,
        discount_price: this.addForm.discount_price,
        on_sale: onsale,
        num: this.addForm.num,
      }).then(res => {
        if (res.data.code == 200) {
          this.$message.success('添加成功')
          this.productVisible = false
        } else {
          this.productVisible = false
        }
      })
    },
    handleChange(info) {
      if (info.file.response.code == 200) {
        this.addForm.img_path = info.file.response.data
        this.imgList.push(info.file.response.data)
        this.$message.success('上传图片成功')
      }
    },
    closeDrawer() {
      this.visible = false
    },
    editUser(record) {
      request(process.env.VUE_APP_API_BASE_URL1 + '/product/' + record.id, 'delete', {
      }).then(res => {
        if (res.data.code == 200) {
          this.getData()
        }
      })
    },
    onPageChange(page, pageSize) {
      this.pagination.current = page
      this.pagination.pageSize = pageSize
      this.getData()
    },
    getData() {
      request(process.env.VUE_APP_API_BASE_URL1 + '/products', 'get', {
        page: this.pagination.current,
        pageSize: this.pagination.pageSize,
        username: this.inputForm.nickname,
        mobile: this.inputForm.mobile,
        status: this.inputForm.status,
        create: this.convertToTimestamp(this.inputForm.createAt) ? this.convertToTimestamp(this.inputForm.createAt) : ''
      }).then(res => {
        const { list, page, pageSize, total } = res?.data?.data ?? {}
        let dataSource = []
        if (list) {
          list.forEach(item => {
            item['key'] = item.id
            item.created_at = item.created_at * 1000
            dataSource.push(item)
          });
          this.$message.success('查询信息成功')
        } else {
          // this.$message.error('未找到相对应的数据，请检查搜索条件')
        }
        this.dataSource = dataSource
        this.pagination.current = page
        this.pagination.pageSize = pageSize
        this.pagination.total = total
      })
    },
    convertToTimestamp(datetime) {
      if (datetime != "") {
        const date = new Date(datetime);
        let timestamp = Math.floor(date.getTime());
        timestamp = moment(timestamp).startOf('day').unix()
        return timestamp
      }
      return ""
    },
    resetInputForm() {
      this.inputForm = {}
    },
    deleteRecord(record) {
      request(process.env.VUE_APP_API_BASE_URL1 + '/products/' + record.id, 'put', {
      }).then(res => {
        if (res.data.code == 200) {
          this.getData()
        }
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    remove() {
      this.dataSource = this.dataSource.filter(item => this.selectedRows.findIndex(row => row.key === item.key) === -1)
      this.selectedRows = []
    },
    onClear() {
      this.$message.info('您清空了勾选的所有行')
    },
    onStatusTitleClick() {
      this.$message.info('你点击了状态栏表头')
    },
    onChange(e) {
      console.log('e :>> ', e);
      this.$message.info('表格状态改变了')
    },
    onSelectChange() {
      // this.$message.info('选中行改变了')
    },
    closeProductDrawer() {
      this.productVisible = false
    },
    addNew() {
      this.productVisible = true
      this.getCategory()
    },
    getCategory() {
      categorys().then(result => {
        let list = result.data.data
        let flist = []
        let slist = []
        let tlist = []
        for (let i = 0; i < list.length; i++) {
          if (!list[i].pid) {
            let obj = {
              value: list[i].id,
              label: list[i].name,
              children: []
            }
            flist.push(obj);
          } else if (!list[i].picture) {
            slist.push(list[i]);
          } else {
            tlist.push(list[i]);
          }
        }

        for (let i = 0; i < flist.length; i++) {// 第一层 一级分类
          for (let j = 0; j < slist.length; j++) {// 第二层 二级分类
            if (slist[j].pid == flist[i].value) {
              let obj = {
                value: slist[j].id,
                label: slist[j].name,
                children: []
              }
              flist[i].children.push(obj)
            }
          }
        }

        for (let i = 0; i < flist.length; i++) { //第三层 三级分类
          for (let j = 0; j < flist[i].children.length; j++) {
            for (let k = 0; k < tlist.length; k++) {
              if (tlist[k].pid == flist[i].children[j].value) {
                let obj = {
                  value: tlist[k].id,
                  label: tlist[k].name,
                }
                flist[i].children[j].children.push(obj)
              }
            }
          }
        }
        this.flist = flist
      })
    },
    handleMenuClick(e) {
      if (e.key === 'delete') {
        this.remove()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}

.fold {
  width: calc(100% - 216px);
  display: inline-block
}

.operator {
  margin-bottom: 18px;
}

@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
</style>
